﻿/******************************* 
** 作者： 斯泰尔 
** 时间： 2021-09-08 10:39:59 
** 版本: V1.0.0 
** CLR: 4.0.30319.42000 
** GUID: 768f475a-2630-4f7e-83d2-f89a65dc03eb 
** 描述： 尚未编写描述 
*******************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FDA_Code
{
    class InitFile
    {
        #region 使DataGridView的列自适应宽度
        /// <summary>
        /// 使DataGridView的列自适应宽度
        /// </summary>
        /// <param name="dgViewFiles"></param>
        public void AutoSizeColumn(System.Windows.Forms.DataGridView dgViewFiles)
        {
            int width = 0;
            dgViewFiles.ColumnHeadersDefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            //使列自使用宽度
            //对于DataGridView的每一个列都调整
            for (int i = 0; i < dgViewFiles.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                dgViewFiles.AutoResizeColumn(i, System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个DataGridView的宽度
                width += dgViewFiles.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系，如果是调整后的宽度大于原来设定的宽度，
            //则将DataGridView的列自动调整模式设置为显示的列即可，
            //如果是小于原来设定的宽度，将模式改为填充。
            if (width > dgViewFiles.Size.Width)
            {
                dgViewFiles.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                dgViewFiles.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            }
        }
        #endregion

        #region DataGridView标题字段转换
        /// <summary>
        /// DataGridView标题字段转换
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dGV"></param>
        /// <param name="NoDispFld"></param>
        public void DataViewColumn(System.Data.DataTable dt, System.Windows.Forms.DataGridView dGV, string NoDispFld="")
        {
            try
            {
                string[] NocolName = NoDispFld.Split(',');
                string items = "";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    items += "'" + dt.Columns[i].ToString().Trim() + "',";
                }
                items = items.LastIndexOf(",") == items.Length - 1 ? items.Remove(items.Length - 1, 1) : items;

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    string colName = dt.Columns[i].ColumnName.ToString().ToLower().Trim();
                    dGV.Columns[i].Name = colName;
                    dGV.Columns[i].ToolTipText = colName;
                    dGV.Columns[i].HeaderText = dictionary(colName);
                    if (colName == "id" || colName == "totalnum")
                    {
                        dGV.Columns[i].Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString(), true);
            }
        }


        public void DataViewColumn(System.Windows.Forms.DataGridView dGV, string NoDispFld)
        {
            try
            {
                /*
                string[] NocolName = NoDispFld.Split(',');
                string items = "";
                for (int i = 0; i < dGV.Columns.Count; i++)
                {
                    items += "'" + dGV.Columns[i].Name.ToString().Trim() + "',";
                }
                items = items.LastIndexOf(",") == items.Length - 1 ? items.Remove(items.Length - 1, 1) : items;
                */
                for (int i = 0; i < dGV.Columns.Count; i++)
                {
                    string colName = dGV.Columns[i].Name.ToString().ToLower().Trim();
                    dGV.Columns[i].Name = colName;
                    dGV.Columns[i].ToolTipText = "字段名：" + colName;
                    dGV.Columns[i].HeaderText = colName == "sel" ? dGV.Columns[i].HeaderText : dictionary(colName);
                    if (colName == "id" || colName == "totalnum")
                    {
                        dGV.Columns[i].Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString(), true);
            }
        }

        public string DatatableColumnsToString(System.Data.DataTable dt, string table, string sql, string method)
        {
            string result = "";
            string itemName = "";
            switch (method)
            {
                case "insert":
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        itemName += dt.Columns[i].ToString().Trim() + ",";
                    }
                    itemName = itemName.LastIndexOf(",") == itemName.Length - 1 ? itemName.Remove(itemName.Length - 1, 1) : itemName;

                    result += "insert into " + table + "(" + itemName + ")" + sql + ";";
                    break;
                case "update":
                    break;
                default:
                    break;
            }
            return result;
        }

        private string dictionary(string param)
        {
            string result = "";
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("code", "操作员");
            dict.Add("erp_id", "单据编号");
            dict.Add("created_at", "时间");
            dict.Add("partner_code", "单位编号");
            dict.Add("fda_code", "监管码");
            dict.Add("partner_name", "企业名称");
            
            result = dict.ContainsKey(param.ToLower()) ? dict[param.ToLower()] : param;
            return result;
        }
        #endregion

        #region 错误日志
        public void WriteLog(string msg, bool isdebug)
        {
            string text = AppDomain.CurrentDomain.BaseDirectory;
            text = Path.Combine(text, "log");
            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            if (isdebug)
            {
                text = Path.Combine(text, "debug");
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
            }
            text = Path.Combine(text, DateTime.Now.ToString("yyyyMMdd") + ".txt");
            if (!File.Exists(text))
            {
                File.CreateText(text).Close();
            }
            StreamWriter streamWriter = new StreamWriter(text, true, Encoding.UTF8);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.WriteLine("{0}  {1}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"), msg);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.Flush();
            streamWriter.Close();
        }

        public void ClearLog()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
            if (Directory.Exists(path))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
                FileInfo[] array = files;
                for (int i = 0; i < array.Length; i++)
                {
                    FileInfo fileInfo = array[i];
                    if (DateTime.Now.Subtract(fileInfo.CreationTime).Days > 30)
                    {
                        File.Delete(fileInfo.FullName);
                    }
                }
            }
        }
        #endregion
    }
}
